package com.tucy.logistics.security.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.tucy.logistics.common.result.ServiceException;
import com.tucy.logistics.handler.InterceptorHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * author: tcy
 * createDate: 2023/8/15
 * description:
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，定义详细认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 指定一条 match 规则
            SaRouter.notMatch("/user/login","/captcha/**","/menu/**",
                              "/doc.html",
                              "/*/doc.html",
                              "/v2/api-docs",
                              "/*/v2/api-docs",
                              "/swagger-resources",
                              "/swagger-resources/**",
                              "/webjars/**",
                              "/favicon.ico")                   // 排除掉的 path 列表，可以写多个
                    .check(r -> {
                        if (!StpUtil.isLogin()){
                            throw new ServiceException(401,"令牌失效");
                        }
                    });
        })).addPathPatterns("/**");

        //拦截，将登录信息放入请求头
        registry.addInterceptor(new InterceptorHandler());
    }
}
